#include "pch.h"
#include "D3DResource.h"
#include "ErrorCodes.h"

using namespace Platform;
using namespace Microsoft::WRL;

using namespace DXBase;
using namespace DXBase::D3D;

MappedSubresource^ DXBase::D3D::Resource_Map(IResource^ resource, uint32 subresource, D3D::Map mapType, MapFlag flag)
{
	auto nr = resource->GetNativeResource();
	if (!nr || !nr->resource)
		return nullptr;
	auto mt = static_cast<D3D11_MAP>(mapType);
	auto f = static_cast<D3D11_MAP_FLAG>(flag);
	D3D11_MAPPED_SUBRESOURCE mapped;
	HR2Ex(resource->Context->m_d3dContext->Map(nr->resource.Get(), subresource, mt, f, &mapped));
	return ref new MappedSubresource(resource, subresource, mapped);
}
void DXBase::D3D::Resource_CopyTo(IResource^ src, IResource^ dst)
{
	if (!src || !dst)
		throw ref new NullReferenceException();
	if (!src->Context)
		throw ExHelper::CreateException(ErrorCodes::ContextNotSet);
	if (src->Context != dst->Context)
		throw ExHelper::CreateException(ErrorCodes::ContextDoNotMatch);

	auto nrsrc = src->GetNativeResource();
	auto nrdst = dst->GetNativeResource();
	src->Context->m_d3dContext->CopyResource(nrsrc->resource.Get(), nrdst->resource.Get());
}


MappedSubresource::MappedSubresource(IResource^ res, uint32 subresource, D3D11_MAPPED_SUBRESOURCE& data)
	: resource(res), subresource(subresource)
{
	rowPitch = data.RowPitch;
	depthPitch = data.DepthPitch;
	pData = ref new MemoryBlock((size_t)data.pData, -1);
}

void MappedSubresource::Unmap()
{
	auto nr = resource->GetNativeResource();
	if (!nr || !nr->resource)
		return;
	auto ctxt = resource->Context;
	if (!ctxt)
		return;
	auto cd3 = ctxt->m_d3dContext;
	if (!cd3)
		return;
	cd3->Unmap(nr->resource.Get(), subresource);
}